package ws

import (
	"encoding/json"
	"fmt"
	"github.com/jackc/pgtype"
	"golang.org/x/net/websocket"
	"sync"
)

type WsMessage struct {
	Id   int              `json:"id,omitempty"`
	Type int8             `json:"type,omitempty"` // 0 系统 1 用户
	Msg  string           `json:"msg"`
	From string           `json:"from"`
	To   string           `json:"to,omitempty"`
	At   pgtype.Timestamp `json:"at"`
}

var connMap = make(map[string]*websocket.Conn)
var mlk sync.Mutex

func init() {
	//http.Handle("/ws", websocket.Handler(WsHandle))
}

func WsHandle(ws *websocket.Conn) {
	var err error
	for {
		var reply string

		if err = websocket.Message.Receive(ws, &reply); err != nil {
			// todo
			//fmt.Println(err.Error())
			//fmt.Println("Can't receive")
			break
		}

		wsmsg := WsMessage{}
		err := json.Unmarshal([]byte(reply), &wsmsg)
		if err != nil {
			fmt.Println(err.Error())
		}

		//fmt.Println(wsmsg.Msg, wsmsg.Id, wsmsg.From)

		if wsmsg.Type == 0 && wsmsg.From != "" {
			mlk.Lock()
			connMap[wsmsg.From] = ws
			mlk.Unlock()
			fmt.Println("add connect")
		}
		if wsmsg.Type == 2 && wsmsg.From != "" {
			mlk.Lock()
			delete(connMap, wsmsg.From)
			mlk.Unlock()
			fmt.Println("delete connect")
		}
		for k, v := range connMap {
			go sendMessage(wsmsg, v, k)
		}
		//for k, v := range connMap {
		//	fmt.Println(k, v)
		//}
		//fmt.Println("---")
	}
}

func sendMessage(replyMsg WsMessage, conn *websocket.Conn, uid string) {
	if uid == replyMsg.From {
		//todo db op
	}
	js, _ := json.Marshal(&replyMsg)

	if err := websocket.Message.Send(conn, string(js)); err != nil {
		fmt.Println(err.Error())
		fmt.Println("Can't send")
		err := connMap[uid].Close()
		mlk.Lock()
		delete(connMap, uid)
		mlk.Unlock()
		if err != nil {
			fmt.Println(err.Error())
			return
		}

	}
}
